package pikes.core;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

/**
 * Base View class which can generate character content. The content is represented as subclass of {@link Printable}. 
 * @author Peter Bona
 *
 */
public abstract class TextView extends AbstractView {

    	/**
    	 * Generates character content and prints it to the http servlet respone.
    	 * The content is generated by {@link #createContent(Map, HttpServletRequest)}
    	 * and it is printed by {@link #printContent(Printable, PrintWriter)}.
    	 * After printing the content, the http servlet output is flushed.
    	 *  
    	 */
	@Override
	protected final void renderMergedOutputModel(final Map model, final HttpServletRequest request,
			final HttpServletResponse response) throws Exception {
		response.setContentType(getContentType());

		PrintWriter writer = response.getWriter();

		Printable content = createContent(model, request);

		printContent(content, writer);

		writer.flush();
	}

	/**
	 * Generates the character content which will be sent back to the browser.
	 * @param model
	 * @param request
	 * @return character content
	 * @throws Exception
	 */
	protected abstract Printable createContent(Map model, HttpServletRequest request) throws Exception;

	/**
	 * Prints the character content to the http servlet response. Subclasses should override this method if special formatting is required.
	 * @param printable generated by {@link #createContent(Map, HttpServletRequest)}
	 * @param responseWriter retrieved by {@link HttpServletResponse#getWriter()}
	 * @throws Exception
	 */
	protected abstract void printContent(Printable printable, PrintWriter responseWriter) throws Exception;
}
